package fenetres;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

import controles.Utilisateur;
import database.DBManager;

public class Authentification extends JInternalFrame implements ActionListener{
	JPanel fondPanel;
	JTextField loginTxt;
	JPasswordField mdpTxt;
	JButton connexBut, cancelBut;
	
	Utilisateur userConnected;
	
	public Authentification(){
		super("Authentification",
	              false, //resizable
	              true, //closable
	              false, //maximizable
	              false);//iconifiable
		fondPanel = new JPanel();
		etablishPanel();
		this.getContentPane().setLayout(null);
		this.getContentPane().add(fondPanel);
		//this.setBounds(500,150,300,200);
		setLocation(60, 60);
		this.setSize(300,200);
		this.setTitle("Authentification");
		this.setVisible(true);
		this.setResizable(false);
	}
	
	public void etablishPanel(){
		fondPanel.setLayout(null);
		fondPanel.setBounds(0,0,300,200);
		
		//champ de saisie
		JLabel loginLab = new JLabel("Login: ");
		loginTxt = new JTextField();
		JLabel mdpLab =  new JLabel("Password: ");
		mdpTxt = new JPasswordField();
		
		//Bouttons
		connexBut = new JButton("Connecter");
		connexBut.addActionListener(this);
		cancelBut = new JButton ("Annuler");
		cancelBut.addActionListener(this);
		
		fondPanel.add(loginLab);
		fondPanel.add(loginTxt);
		fondPanel.add(mdpLab);
		fondPanel.add(mdpTxt);
		fondPanel.add(connexBut);
		fondPanel.add(cancelBut);
		
		//position des objets
		loginLab.setBounds(5,5,100,30);
		loginTxt.setBounds(120,5,120,30);
		mdpLab.setBounds(5,50,100,30);
		mdpTxt.setBounds(120,50,120,30);
		connexBut.setBounds(20,120,120,30);
		cancelBut.setBounds(160,120,120,30);
	}
	
	public Utilisateur getUserConnected(){
		return userConnected;
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		if(arg0.getSource() == connexBut){
			String login = loginTxt.getText();
			String passwd = mdpTxt.getText();
			
			DBManager dbManager = new DBManager();
			userConnected = dbManager.existUser(login, passwd);
			if(userConnected == null){
				JOptionPane.showMessageDialog(null, "Login ou mot de passe incorrect !!!","Erreur",JOptionPane.ERROR_MESSAGE);
				loginTxt.setText("");
				mdpTxt.setText("");
			}
			else{
				this.dispose();
				String message = "Vous êtes connectés entant que "+userConnected.getNom()+"";
				JOptionPane.showMessageDialog(null,message ,"Confirmation",JOptionPane.INFORMATION_MESSAGE);
			}
		}
		else if (arg0.getSource() == cancelBut){
			this.setVisible(false);
		}
		
	}
}
